let Pages = require('./pages.js')
let utils = require('./utils.js')
let request = require('./request.js')
let Application = require('./application.js')

let config = {
    http: {
        root: 'http://127.0.0.1:7001/api',
        // root: 'http://192.168.18.127:7001/api',
        // root: 'https://choujiang.58jinbao.com/api',
        header: {},
        duration: 1,
        timestamp: false,
        error: (message) => {
            we.showModal({content: message, title: "网络错误", showCancel: true})
        }
    }
}

function we(obj = {}) {
    Pages.prototype.$post = http('POST')
    Pages.prototype.$get = http('GET')

    Application.prototype.$post = http('POST')
    Application.prototype.$get = http('GET')
}


utils.toPromise(we, wx)
we.request = request(config.http)

we.Page = Pages
we.App = Application

Pages.global = we
Application.global = we

module.exports = we

let http = (method = 'GET') => {
    return (url, data = {}, header = {}) => {
        header['session'] = wx.getStorageSync('sid')
        return we.request({
            url: url,
            header,
            method,
            data: data,
            duration: 1,
        }).then(res => {
            if (res.data.status === 0) {
                return Promise.resolve(res.data.data)
            } else if (res.data.status === -1) {
                wx.removeStorageSync('sid')
                wx.showToast({icon: 'none', title: '登录失效,为您重新登录...'})
                wx.reLaunch({url: "/pages/index/index"})
            } else {
                if (res.data.message && res.data.resultMsg) {
                    return Promise.reject(res.data)
                } else {
                    return Promise.reject({message: res.data.message || '未知的服务器错误'})
                }
            }
        }, err=> {
            return Promise.reject({message: err.msg})
        })
    }
}


